package com.generator.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Data
@Component
public class ServiceConfig implements InitializingBean {

    @Value("${election.timeout:5000}")
    private int electionTimeout;

    @Value("${coordinator.address}")
    private String coordinatorAddress;

    /**
     * 协调者连接超时时间(ms)
     */
    @Value("${coordinator.connection.timeout:5000}")
    private int coordinatorConnectionTimeout;

    /**
     * 协调者会话超时时间(ms)
     */
    @Value("${coordinator.session.timeout:10000}")
    private int coordinatorSessionTimeout;

    /**
     * 协调者重试次数
     */
    @Value("${coordinator.retry.times:3}")
    private int coordinatorRetryTimes;

    /**
     * 协调者重试间隔(ms)
     */
    @Value("${coordinator.retry.interval:1000}")
    private int coordinatorRetryInterval;

    @Value(("${spring.application.name}"))
    private String appName;

    /**
     * epoch 值所占比特位数,默认29,那么sequence就占用34位
     */
    @Value("${epoch.bits:29}")
    private int epochBits;

    @Value("${worker.bits:16}")
    private int workerBits;

    @Value("${worker.id:1}")
    private int workerId;

    @Value("${data.center.bits:0}")
    private int dataCenterBits;

    @Value("${data.center.id:0}")
    private int dataCenterId;

    /**
     * sequence 剩余百分比,达到或低于次值则触发申请新的区间
     */
    @Value("${sequence.remain.percent:20}")
    private int sequenceRemainPercent;

    @Override
    public void afterPropertiesSet() throws Exception {
        if(epochBits <= 0 || epochBits > 31) {
            log.error("配置项的 [{}] 配置范围需在[15,29]之间","epoch.bits");
            // 终止虚拟机
            System.exit(-1);
        }

        if(workerBits <= 0 || workerBits >= 22) {
            log.error("配置项的 [{}] 配置范围需在(0,22)之间","workerBits");
            System.exit(-1);
        }

        if(dataCenterBits < 0 || dataCenterBits >= 21) {
            log.error("配置项的 [{}] 配置范围需在[0,21)之间","dataCenterBits");
            System.exit(-1);
        }
    }
}
